package com.letoy.edu.socket.controller;


import com.letoy.edu.service.VenuesInfoService;
import com.letoy.edu.socket.model.MyMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller
public class ChatController {
    @Resource
    VenuesInfoService venuesInfoService;

    @Resource
    SimpMessagingTemplate simpMessagingTemplate;

    @MessageMapping("/chat.sendMessage")
    @SendTo("/topic/public")
    public MyMessage sendMessage(@Payload MyMessage myMessage){
        System.out.println(myMessage.toString());
        if(myMessage.getState().equals("update")){
            venuesInfoService.updateVenuesInfoByIdFromMyMessage(myMessage);
        }
        return myMessage;
    }

    @MessageMapping("/chat.sendToUser")
    public MyMessage sendMessageToUser(@Payload MyMessage myMessage){
        System.out.println(myMessage.getSender());
        String user = myMessage.getSender();
        simpMessagingTemplate.convertAndSendToUser(user,"/queue/message","nihao");
        return myMessage;
    }

    /**
     *
     * @param myMessage
     * @param headerAccessor
     * @return
     */
    @MessageMapping("/chat.addUser")
    @SendTo("/topic/public")
    public MyMessage addUser(@Payload MyMessage myMessage,
                               SimpMessageHeaderAccessor headerAccessor){
        headerAccessor.getSessionAttributes().put("username",myMessage.getSender());
        System.out.println(myMessage.getSender());
        return myMessage;
    }


}
